package org.example.ExperimentTwo;

import java.util.function.Supplier;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class TimeUtils {

    public static <T> T measureTime(Callable<T> task) {
        long startTime = System.nanoTime();// 记录开始时间
        try {
            ExecutorService executor = Executors.newSingleThreadExecutor();
            Future<T> future = executor.submit(task);
            T result = future.get(); // 这里会阻塞直到获取到结果
            long endTime = System.nanoTime(); //记录结束时间
            long duration = endTime - startTime;
            System.out.printf("题目执行的时间为%dseconds", duration);
            executor.shutdownNow(); // 关闭线程池
            return result;
        } catch (InterruptedException | ExecutionException e) {
            throw new RuntimeException(e);
        }
    }
}